<?php
/**
 * Created by PhpStorm.
 * User: Tom
 * Date: 2018/7/14
 * Time: 11:39
 */

namespace Home\Controller;
define("TOKEN", C('Wechat.TOKEN'));//定义你公众号自己设置的token
define("APPID", C('Wechat.APPID'));//填写你微信公众号的appid 千万要一致啊
define("APPSECRET", C('Wechat.APPSECRET'));//填写你微信公众号的appsecret  千万要记得保存 以后要看的话就只有还原了  保存起来 有益无害


use Think\Controller;
use \Vendor\Weixin\Wechat ;

class WechatController extends Controller
{

    public $open_id;
    public $wxuser;

    public function test()
    {
        echo TOKEN . "\r\n";
        echo APPID . "\r\n";
        echo APPSECRET . "\r\n";
        session('name',time());

        dump(session('?name'));

    }

    //判断是介入还是用户  只有第一次介入的时候才会返回echostr

    public function index()
    {
        //这个echostr呢  只有说验证的时候才会echo  如果是验证过之后这个echostr是不存在的字段了
        $echoStr = $_GET["echostr"];
        $dumpstr = json_encode($_GET);
        file_put_contents('a.txt', $dumpstr, FILE_APPEND);
        if ($this->checkSignature())
        {
            ob_clean();
            echo $echoStr;
            //如果你不知道是否验证成功  你可以先echo echostr 然后再写一个东西
            exit;
        }
        else
        {
            echo " wa ";
            exit();
        }
    }//index end

    //验证微信开发者模式接入是否成功
    private function checkSignature()
    {
        //signature 是微信传过来的 类似于签名的东西
        $signature = $_GET["signature"];
        //微信发过来的东西
        $timestamp = $_GET["timestamp"];
        //微信传过来的值  什么用我不知道...
        $nonce = $_GET["nonce"];
        //定义你在微信公众号开发者模式里面定义的token
        $token = TOKEN;
        //三个变量 按照字典排序 形成一个数组
        $tmpArr = array(
            $token,
            $timestamp,
            $nonce
        );
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        //哈希加密  在laravel里面是Hash::
        $tmpStr = sha1($tmpStr);
        //按照微信的套路 给你一个signature没用是不可能的 这里就用得上了
        if ($tmpStr == $signature)
        {
            return true;
        }
        else
        {
            return false;
        }
    }// checkSignature end

    //构建一个发送请求的curl方法  微信的东西都是用这个 直接百度
    function https_request($url, $data = null)
    {
        //这个方法我不知道是怎么个意思  我看都是这个方法 就copy过来了
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data))
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }//https_request end


    function getCode()
    {
        header("Content-Type: text/html; charset=UTF-8");
        $code = $_GET["code"];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . APPID . "&secret=" . APPSECRET . "&code=" . $code . "&grant_type=authorization_code";
        $res = $this->https_request($url);
        $res = json_decode($res, true);
        $openid = $res["openid"];
        $access_token = $res["access_token"];
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $res = $this->https_request($url);
        $res = json_decode($res, true);
        foreach ($res as $key => $value)
        {
            echo $value . '<br>';

        }
        dump($res);
        session('wxinfo', $res['openid']);
    }


    public function wxoauth()
    {
        $s_time='token_time';
        $scope = 'snsapi_base';
        $code = isset($_GET['code']) ? $_GET['code'] : '';
        $token_time = session('?'.$s_time)  ? session($s_time) : 0;
        if (!$code && session('?open_id') && session('?user_token') && $token_time > time() - 3600)
        {
            if (!$this->wxuser)
            {
                $this->wxuser = session('wxuser');
            }
            $this->open_id = session('open_id');
            return $this->open_id;
        }
        else
        {
            $options = array(
                'token' => TOKEN, //填写你设定的key
                'appid' => APPID, //填写高级调用功能的app id
                'appsecret' => APPSECRET //填写高级调用功能的密钥
            );
            $we_obj = new Wechat($options);
            if ($code)
            {
                $json = $we_obj->getOauthAccessToken();
                if (!$json)
                {
                    unset($_SESSION['wx_redirect']);
                    die('获取用户授权失败，请重新确认43');
                }
                $this->open_id = $json["openid"];

                session('openid', $json["openid"]);
                $access_token = $json['access_token'];
                session('user_token', $access_token);
                session('token_time', time());

                $userinfo = $we_obj->getUserInfo($this->open_id);
                if ($userinfo && !empty($userinfo['nickname']))
                {
                    $this->wxuser = array(
                        'openid' => $this->open_id,
                        'nickname' => $userinfo['nickname'],
                        'sex' => intval($userinfo['sex']),
                        'province' => $userinfo['province'],
                        'city' => $userinfo['city'],
                        'avatar' => $userinfo['headimgurl']
                    );

                }
                elseif (strstr($json['scope'], 'snsapi_userinfo') !== false)
                {
                    $userinfo = $we_obj->getOauthUserinfo($access_token, $this->open_id);
                    if ($userinfo && !empty($userinfo['nickname']))
                    {
                        $this->wxuser = array(
                            'openid' => $this->open_id,
                            'nickname' => $userinfo['nickname'],
                            'sex' => intval($userinfo['sex']),
                            'province' => $userinfo['province'],
                            'city' => $userinfo['city'],
                            'avatar' => $userinfo['headimgurl']
                        );
                    }


                }
                if ($this->wxuser)
                {
                    session('wxuser', $this->wxuser);
                    session('open_id', $json["openid"]);
                    session('wx_redirect', null);
                    $this->redirect("Index/index",['rnd'=>time()]);
                   // return $this->open_id;
                }
                $scope = 'snsapi_userinfo';
            }
            if ($scope == 'snsapi_base')
            {
                $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                session('wx_redirect', $url);
            }
            else
            {
                $url = session('wx_redirect');
            }
            if (!$url)
            {
                unset($_SESSION['wx_redirect']);
                die('获取用户授权失败88');
            }
            $oauth_url = $we_obj->getOauthRedirect($url, "wxbase", $scope);
            header('Location: ' . $oauth_url);
        }
    }

}